<template lang="pug">
transition(name="dialog")
  .dialog-mask(v-if="show")
    .dialog
      .dialog-header
        .dialog-header-title 添加材料
        .dialog-close
          .iconfont.icon-close(@click.self="close")
      .dialog-content
        .material-info
          .material-img(:style="`background-image: url(${detail.picImg})`")
          .material-info-content
            .material-name {{detail.materialName}}
            .material-brand 品牌：{{detail.brandName}}
            .material-cate {{detail.categoryName}}
        .material-spec
          .material-spec-title 请选择规格
          .spec-list
            .spec-item(v-for="item, index in detail.specAttrList")
              .spec-item-label {{item.name}}：
              .spec-item-bd(:ref="`tag_item_${item.specId}`", :class="item.isHidden ? 'filter-row-bd_hide' : ''")
                .spec-item-tag(v-for="tag in item.values" @click="selectSpec(tag, index)" :class="{'active' : item.activeId === tag.id}") {{tag.value}}
              .spec-item-ft(v-if="item.isMore" @click="showMore(item)") 更多>>
        .project-name 已选项目：{{projectInfo.projectName}}
        .form-item(v-if="projectInfo.customType === 'island'")
          .form-item-label.important 选择业态：
          .form-item-bd
            .form-item-input
              input.form-item-input-bd(placeholder="请选择" v-model="businessName" @click.stop="showOption = !showOption" readonly)
              transition(name="select")
                .select-options(v-show="showOption")
                  .option-item(v-for="item in newBusiness" @click.stop="selectOptionItem(item)") {{item.title}}
        .form-item
          .form-item-label.important 使用空间：
          .form-item-bd
            .form-item-input
              input.form-item-input-bd(placeholder="请选择" v-model="spaceName" @click.stop="showSpaceOption = !showSpaceOption" readonly)
              transition(name="select")
                .select-options(v-show="showSpaceOption")
                  .option-item(v-for="item in space" @click.stop="selectSpaceOptionItem(item)") {{item.spaceName}}
        .form-item
          .form-item-label 使用区域：
          .form-item-bd
            .form-item-input
              input.form-item-input-bd(placeholder="请输入使用区域" v-model="form.appliedArea")
      .dialog-footer
        .dialog-button(@click="close") 取消
        .dialog-button.confirm(@click="confirm") 添加
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { getSampleMaterialDetail, getProjectSpaceCategory, getBusinessTypeList, getSpaceList, joinProjectIsland, joinProject } from 'api'
export default {
  name: 'materialModal',
  computed: {
    ...mapState({
      show: state => state.ui.material.show,
      projectInfo: state => state.ui.material.item,
      sampleDetail: state => state.ui.material.detail
    }),
    spaceName () {
      let item = this.space.find(item => item.spaceId === this.form.spaceId[0])
      return item ? item.spaceName : ''
    },
    businessName () {
      let item = this.newBusiness.find(item => item.id === this.form.businessType)
      return item ? item.title : ''
    },
  },
  watch: {
    async show (v) {
      if (v) {
        if (this.projectInfo.customType === 'island') this.getFormats()
        else this.getProjectSpace()
        await this.getDetail()
        this.detail.specAttrList.map(item => {
          this.setMoreIcon(item)
        })
      }
    }
  },
  data () {
    return {
      showOption: false,
      showSpaceOption: false,
      key: '',
      form: {
        spaceId: [],
        appliedArea: '',
        num: 1,
        businessType: ''
      },
      detail: {
        specAttrList: []
      },
      specKeys: [],
      space: [],
      newBusiness: []
    }
  },
  methods: {
    ...mapActions([
      'changeAddMaterial',
    ]),
    async confirm () {
      try {
        if (!this.key) {
          this.message({ show: true, content: '请先选择材料规格！', type: 'error' })
          return
        }
        if (!this.form.spaceId.length) {
          this.message({ show: true, content: '请先选择使用空间！', type: 'error' })
          return
        }
        if (this.projectInfo.customType === 'island') {
          await this.$axios.post(joinProjectIsland, { ...this.form, projectId: this.projectInfo.id, projectName: this.projectInfo.name, specKey: this.key, materialId: this.sampleDetail.materialId, roleIds: this.projectInfo.role_ids })
        } else {
          delete this.form.businessType
          await this.$axios.post(joinProject, { ...this.form, projectId: this.projectInfo.projectId, specKey: this.key, materialId: this.sampleDetail.materialId })
        }
        this.message({ show: true, content: '成功加入项目！', type: 'success' })
        this.close()
      } catch (err) {
        console.log(err)
        this.message({ show: true, content: err.message || err.ResultSet.errors, type: 'error' })
      }
    },
    close () {
      this.form = {
        spaceId: [],
        appliedArea: '',
        num: 1,
        businessType: ''
      }
      this.key = ''
      this.detail = {}
      this.specKeys = []
      this.changeAddMaterial({ show: false, item: {}, detail: {} })
    },
    selectSpaceOptionItem (item) {
      this.form.spaceId = [item.spaceId]
      this.showSpaceOption = false
    },
    selectOptionItem (item) {
      this.form.businessType = item.id
      this.showOption = false
    },
    selectSpec (row, index) {
      this.detail.specAttrList.map(item => item.values.map(v => {
        if (row.id === v.id) {
          item.activeId = row.id
          // if (row.fileUrl) this.previewImg = row.fileUrl
        }
      }))
      this.specKeys[index] = row.id
      let newSpecKeys = Array.from(this.specKeys)
      let valid = []
      newSpecKeys.forEach(item => {
        if (item !== undefined) {
          valid.push(item)
        }
      })
      if (valid.length === this.detail.specAttrList.length) {
        this.key = Array.from(new Set(this.specKeys)).sort((a, b) => { return a - b }).join('_')
      }
    },
    showMore (item) {
      item.isHidden = !item.isHidden
    },
    setMoreIcon (item) {
      this.$nextTick(() => {
        let itemHeight = this.$refs[`tag_item_${item.specId}`][0].clientHeight
        if (itemHeight > 40) {
          item.isHidden = true
          item.isMore = true
        } else {
          item.isMore = false
        }
      })
    },
    async getProjectSpace () {
      try {
        const { ResultSet } = await this.$axios.post(getProjectSpaceCategory, { projectId: this.projectInfo.projectId })
        this.$nextTick(() => {
          this.space = ResultSet.userData.projectSpace
        })
      } catch (err) {
        console.log(err)
        this.message({ show: true, content: err.message || err.ResultSet.errors, type: 'error' })
      }
    },
    async getFormats () {
      try {
        const { ResultSet } = await this.$axios.post(getBusinessTypeList)
        this.setBusiness(ResultSet.userData.businessList.value)
        // this.businessList = ResultSet.userData.businessList.value
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    setBusiness (businessList) {
      // let currentItem = this.projectIslandList.find(item => item.id === this.projectInfo.id)
      let business = this.projectInfo.business_type.split(',')
      let newBusiness = []
      businessList.forEach(item => {
        business.forEach(row => {
          if (item.id === parseInt(row)) newBusiness.push(item)
        })
      })
      this.form.businessType = newBusiness[0].id
      this.newBusiness = newBusiness
      this.getSpaceList()
    },
    async getSpaceList () {
      try {
        const { ResultSet } = await this.$axios.post(getSpaceList, { projectId: this.projectInfo.id, businessType: this.form.businessType, type: 3 })
        // ResultSet.userData.result.forEach(item => {
        //   item.isEdit = false
        // })
        this.space = ResultSet.userData.result
      } catch (err) {
        console.log(err)
        this.message({ show: true, content: err.message || err.ResultSet.errors, type: 'error' })
      }
    },
    async getDetail () {
      try {
        const { ResultSet } = await this.$axios.post(getSampleMaterialDetail, { materialId: this.sampleDetail.materialId })
        ResultSet.userData.detail.specAttrList.map((item, index) => {
          item.activeId = ''
          item.isHidden = false
          item.isMore = false
        })
        this.detail = ResultSet.userData.detail
      } catch (err) {
        this.message({ show: true, content: err.message || err.ResultSet.errors, type: 'error' })
      }
    }
  }
} 
</script>

<style type="text/css" lang="scss">
.modal-form-item-code {
  .el-input__inner {
    padding-right: 90px;
  }
}
</style>

<style lang="scss" scoped>
.dialog-leave-active {
  transition: opacity .3s ease;
}
.dialog-enter-active,.dialog-leave-active {
  opacity: 0
}
.dialog-enter-active .select-options,
.dialog-leave-active .select-options {
  transform: scale(0);
  opacity: 0;
}
.select-leave-active {
  transition: opacity .1s ease;
}
.select-enter-active,.select-leave-active {
  opacity: 0
}
.dialog-enter-active .dialog,
.dialog-leave-active .dialog {
  transform: scale(0);
  opacity: 0;
}
.dialog-mask {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 8888;
  background: rgba(0,0,0,.5)
}
.dialog {
  transition: all .3s;
  position: fixed;
  width: 500px;
  // max-height: 650px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) scale(1);
  background: #fff;
  z-index: 9999;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
}
.dialog-header {
  padding: 15px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #F2F2F2;
  .dialog-header-title {
    font-size: 20px;
    font-weight: bold;
  }
  .iconfont {
    font-size: 18px;
    color: #999;
  }
}
.dialog-content {
  padding: 20px;
  max-height: 520px;
}
.material-info {
  display: flex;
  align-items: center;
  .material-img {
    width: 200px;
    height: 150px;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
  }
  .material-info-content {
    flex: 1;
    padding-left: 20px;
    .material-name {
      font-size: 24px;
      font-weight: bold;
      color: #000;
      display: -webkit-box;
      overflow: hidden;
      text-overflow: ellipsis;
      word-wrap: break-word;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    .material-brand {
      margin-top: 15px;
      font-size: 18px;
    }
    .material-cate {
      font-size: 18px;
      margin-top: 5px;
    }
  }
}
.material-spec {
  margin-top: 10px;
}
.material-spec-title {
  font-size: 18px;
  color: #CD9E78;
  font-weight: bold;
}
.project-name {
  margin-top: 10px;
  font-size: 18px;
  color: #CD9E78;
  font-weight: bold;
}
.spec-item {
  margin-top: 10px;
  display: flex;
  .spec-item-label {
    line-height: 32px;
    font-size: 18px;
  }
  .spec-item-ft {
    line-height: 32px;
    font-size: 18px;
    color: #CD9E78;
  }
  .spec-item-bd {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    padding: 0 8px;
    &.filter-row-bd_hide {
      height: 40px;
      overflow: hidden;
    }
    .spec-item-tag {
      font-size: 18px;
      margin-right: 8px;
      margin-bottom: 8px;
      padding: 3px 10px;
      border: 1px solid #dcdfe6;
      &.active {
        border-color: #ff2e42;
        color: #ff2e42;
      }
    }
  }
}
.form-item {
  display: flex;
  margin-top: 15px;
  .form-item-label {
    line-height: 32px;
    font-size: 18px;
    min-width: 100px;
    &.important {
      &:before {
        content: '*';
        margin-right: 4px;
        color: #ff2e42;
      }
    }
  }
  .form-item-bd {
    padding-left: 8px;
    flex: 1;
    .form-item-input {
      height: 32px;
      display: flex;
      align-items: center;
      padding: 0 10px;
      font-size: 18px;
      border: 1px solid #dcdfe6;
      position: relative;
      .form-item-input-bd {
        width: 100%;
        height: 100%;
        font-size: 18px;
      }
      .select-options {
        transition: all .1s;
        position: absolute;
        width: 100%;
        top: 100%;
        left: 0;
        transform: translateY(10px) scale(1);
        border: 1px solid #e4e7ed;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
        background: #fff;
        z-index: 2000;
        .option-item {
          height: 32px;
          display: flex;
          align-items: center;
          padding: 0 10px;
          font-size: 16px;
        }
      }
    }
  }
}
.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 10px 20px;
  .dialog-button {
    padding: 10px 20px;
    font-size: 20px;
    margin-left: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 5px;
    color: #606266;
    line-height: 1;
    &.confirm {
      border-color: #ff2e42;
      background: #ff2e42;
      color: #fff;
    }
  }
}
</style>
